package com.ws.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class FileUploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest req) {
        System.out.println(file);

        String filename = file.getOriginalFilename();
        System.out.println("上传的文件名:"+filename);

        String path = req.getServletContext().getRealPath("upload/");
        System.out.println(path);

        filename = path + new SimpleDateFormat("YYYYMMDDHHmmss").format(new Date()) + "_" + filename;
        System.out.println("保存到服务器的文件名：" + filename);

        File dest = new File(filename);

        try {
            file.transferTo(dest);
            System.out.println("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "文件上传";
    }
}
